import { createSelectBox } from "../utils/utils.js"
import { getStore, setStore } from "../utils/store.js"
import { requests } from "../utils/request.js"
import { VERSION, GIT_ADDRESS } from "../../config/index.js"

export class HeaderComponent {
    static name = "header-component"
    languageKey = getStore("languageKey", "CN")//当前语言KEY
    languageFn = null//语言切换时，给外部执行得方法
    #languageList = []//语言列表
    #tabbarList = []//顶部tabbar列表
    #theme = getStore('theme')//主题
    #header = null//header元素
    constructor() {
        this.#getData()
        this.#themeSwitch(true)
    }
    //配置数据请求
    #configDataHttp() {
        return requests.get("/data/header/config.json")
    }
    //tabbar数据请求
    #tabbarListHttp() {
        return requests.get(`/data/header/${this.languageKey}.json`)
    }
    //获取数据
    #getData() {
        Promise.allSettled([this.#configDataHttp(), this.#tabbarListHttp()]).then(res => {
            const list = res.filter(item => item.status === "fulfilled").map(item => item.value)
            const data = {}
            list.forEach(item => {
                const arr = Object.keys(item)
                arr.forEach(key => {
                    data[key] = item[key]
                })
            })
            this.#languageList = data.LANGUAGE_LIST || []
            this.#tabbarList = data.TABBAR_LIST || []
            this.#createHeaderContainer()
        })
    }
    //创建自定义事件
    #createCustomEvent(key, { paramName, param }) {
        const event = new CustomEvent(key, {
            detail: {
                [paramName]: param
            }
        })
        window.dispatchEvent(event)
    }
    #languageSwitch(e) {//语言切换
        const val = e.target.getAttribute('data-value')
        const label = e.target.getAttribute('data-label')
        if (val && this.languageKey !== val) {
            const items = Array.from(document.getElementsByClassName("select-flyout-item"))
            items.forEach(item => {
                const ival = item.getAttribute('data-value')
                if (ival === val) {
                    item.setAttribute('class', "select-flyout-item select-flyout-item-active")
                } else {
                    item.setAttribute('class', "select-flyout-item")
                }
            })
            document.getElementsByClassName("select-box-text")[0].innerText = label
            this.languageKey = val
            setStore('languageKey', val)
            this.#updateFn()
            if (this.languageFn) {
                this.languageFn()
            }
        }
    }
    #themeSwitch(tf = false) {//主题切换
        if (this.#theme && tf === false) {
            this.#theme = this.#theme === "dark" ? "light" : "dark"
        } else if (this.#theme == null) {
            this.#theme = "dark"
        }
        setStore('theme', this.#theme)
        document.getElementsByTagName('html')[0].setAttribute('class', this.#theme)
    }
    #createLogo(header) {//创建logo<img width="40px" height="40px" src="../static/images/logo.png" alt="">
        header.innerHTML = `
            <div class="xdj-row xdj-flex-align-center page-logo">
                
                <span class="title">前端基础组件库</span>
            </div>
            `
    }
    #createInfo(header) {//创建信息
        header.innerHTML += `
            <div class="xdj-row page-info xdj-flex-align-center">
                <div class="version">${VERSION}</div>
                <div class="github">
                    <span></span>
                </div>
            </div>
            `
    }
    #createLanguageSwitch(header) {//创建语言切换
        const dom = createSelectBox({
            list: this.#languageList,
            className: "header-nav-select",
            defValue: this.languageKey
        })
        header.appendChild(dom)
    }
    #createThemeSwitch(header) {//创建主题切换
        header.innerHTML += `
            <button class=vt-switch>
                <span class=vt-switch-icon>
                    <img src=../static/images/yl.png />
                    <img src=../static/images/ty.png />
                </span>
            </button>
        `
    }
    #createTabbar(header = this.#header) {//创建Tabbar
        let tab = document.getElementsByClassName("xdj-col-5")
        const lis = this.#tabbarList.map(item => {
            //地址按照/分成数组，取出最后一组
            const fileName = window.location.pathname.split("/").pop();
            //取出.号前面得页面名称
            const name = fileName.split(".")[0]
            //看是否和tabbar中得项匹配
            const isActive = name === item.key
            return `<li data-key=${item.key} class=${isActive ? 'active' : ''}>${item.title}</li>`
        }).join("")
        const str = `
                    <ul class="xdj-row tabbar-list">
                        ${lis}
                    </ul>
                `
        if (tab.length === 0) {
            tab = document.createElement("div")
            tab.setAttribute('class', 'xdj-col-5')
            tab.innerHTML = str
            header.insertBefore(tab, header.childNodes[2])
        } else {
            tab[0].innerHTML = str
        }

    }
    #createHeader() {//创建header
        const header = document.createElement('header')
        const box = document.createElement('div')
        box.setAttribute('class', 'xdj-row')
        this.#header = box
        header.appendChild(box)
        document.body.insertBefore(header, document.body.childNodes[0])
        return box
    }
    #updateTabbar() {//更新tabbar
        this.#tabbarListHttp().then(res => {
            this.#tabbarList = res.TABBAR_LIST
            this.#createTabbar()
        })
    }
    #updateFn() {//更新方法
        this.#updateTabbar()
    }
    #createHeaderContainer() {//创建头部内容
        const header = this.#createHeader()
        this.#createLogo(header)
        this.#createTabbar(header)
        this.#createLanguageSwitch(header)
        this.#createThemeSwitch(header)
        this.#createInfo(header)
        //语言切换
        document.getElementsByClassName("select-flyout")[0].onclick = this.#languageSwitch.bind(this)
        //主题切换
        document.getElementsByClassName("vt-switch")[0].onclick = this.#themeSwitch.bind(this, false)
        // github跳转
        document.getElementsByClassName("github")[0].onclick = () => window.open(GIT_ADDRESS)
        // 首页跳转
        document.getElementsByClassName("page-logo")[0].onclick = () => location.href = `./${this.#tabbarList[0].key}.html`
        // tabbar跳转
        document.getElementsByClassName("xdj-col-5")[0].onclick = this.#tabbarLinkHandle
    }
    #tabbarLinkHandle(e) {//tabbar跳转处理
        const key = e.target.getAttribute("data-key")
        if (key) {
            window.location.href = `../page/${key}.html`
        }
    }
}


